<template>
  <el-card shadow="hover">
  <el-input    v-model="filterText"    placeholder="过滤条件"    prefix-icon="Search"    clearable  />
  <el-tree
    ref="treeRef"
    style="max-width: 600px"
    class="filter-tree"
    :data="dataList"
    :props="defaultProps"
    :expand-on-click-node="false"
    :filter-node-method="filterNode"
    default-expand-all
    highlight-current
    @node-click="nodeSelected"
  />
  </el-card>
</template>

<script lang="ts" setup>
import {defineEmits, defineProps, ref, watch} from 'vue'
import { ElTree } from 'element-plus'
import useDictStore from "@/store/modules/dict";
import {DictVO, getDataByType} from "@/views/system/dict/api";

let filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
let dataList = ref<any>([])

const defaultProps = {
  children: 'children',
  label: 'name',
  id: 'value'
}
const props = defineProps({
  type: { type: String, default: '' },
  value: { type: String, default: '' },
  name: { type: String, default: '' },
});
watch(filterText, (val) => {
  (proxy?.$refs["treeRef"] as any).filter(val) //显示数据过滤
})
const { proxy } = getCurrentInstance() as ComponentInternalInstance
function filterNode(value: string, data: any){
  if (!value) return true
  return data.name.includes(value) //过滤数据
}

const emit = defineEmits(["update:value"]);
/** 选择节点事件 */
function nodeSelected(data: DictVO){
  //为父组件中的v-model更新值，同时调用父组件的update事件
  emit('update:value', data.value)
}

const routeDictType = String(props.type) //获取路由类型数据
async function getTreeList() {
  let res: any;
  const treeData = useDictStore().getDict(routeDictType)
  if (!treeData){
    res = await getDataByType(routeDictType)
    dataList.value = res.data
    useDictStore().setDict(routeDictType,dataList.value)
  }else{
    dataList.value = toRaw(treeData)
  }
  dataList.value = proxy?.handleTree2<DictVO>(dataList.value)
  // console.log(data.value)
}

onMounted(getTreeList)
</script>
